﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using KelonProud.Mvc;
using KelonProud.QuickQuery.Domain;
using KelonProud.QuickQuery.Dtos;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using KelonProud.Data;
using KelonProud.QuickQuery.Managers;
using Microsoft.AspNetCore.Mvc;

namespace KelonProud.QuickQuery.Services
{
    public interface IQueryGridAppService :  IAsyncCrudAppService<QueryGridOutput, int, PagedResultRequestDto, QueryGridInput, QueryGridOutput>
    {
        bool NameIsExists(string name, int id, int? tenantId);
        bool CodeIsExists(string code, int id, int? tenantId);

        Task<List<QueryGridColumnDto>> GenerateGridColumnList(string sql);
    }

    public class QueryGridAppService : KelonProudAsyncCrudAppService<QueryGrid, QueryGridOutput, int, PagedResultRequestDto, QueryGridInput, QueryGridOutput>, IQueryGridAppService
    {
        private readonly QueryGridManager _queryGridManager;

        public QueryGridAppService(IRepository<QueryGrid, int> repository, QueryGridManager queryGridManager) : base(repository)
        {
            _queryGridManager = queryGridManager;
        }

        public override Task<QueryGridOutput> Save(QueryGridInput input)
        {
            throw new NotImplementedException();
        }

        public bool CodeIsExists(string code, int id, int? tenantId)
        {
            return _queryGridManager.CodeIsExists(tenantId, id, code);
        }

        public bool NameIsExists(string name, int id, int? tenantId)
        {

            return _queryGridManager.NameIsExists(tenantId, id, name);
        }

        [HttpPost]
        public Task<List<QueryGridColumnDto>> GenerateGridColumnList(string sql)
        {
            if(sql==null)
                throw new Exception("sql语句不能为空");
            using (var session = DatabaseSession.OpenSession())
            {
                var reader = session.ExecuteReader(sql);
                var table = reader.GetSchemaTable();
            }

            return null;
        }
    }
}
